package org.dejavu.design.prototype;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
* <p>Title: Prototype</p>
* <p>Description: 原型模式</p>
* <p>Company: </p> 
* @author dejavu
* @date 2016-9-7 下午4:19:53
*/
public class Prototype implements Cloneable,Serializable{
	
	private static final long serialVersionUID = 1l;
	
	private String string;
	
	@Override
	public String toString() {
		return "Prototype [string=" + string + ", obj=" + obj + "]";
	}

	private SerializableObject obj;
	
	/**
	 * 浅复制
	 */
	public Object clone() throws CloneNotSupportedException {
		Prototype proto = (Prototype) super.clone();
		return proto;
	}
	
	public Object deepClone() throws IOException, ClassNotFoundException {
		//写入当前对象的二进制流
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject(this);
		//读取出二进制流产生的新对象
		ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
		ObjectInputStream ois = new ObjectInputStream(bis);
		
		return ois.readObject();
	}

	public String getString() {
		return string;
	}

	public void setString(String string) {
		this.string = string;
	}

	public SerializableObject getObj() {
		return obj;
	}

	public void setObj(SerializableObject obj) {
		this.obj = obj;
	}
}

class SerializableObject implements Serializable {  
	private static final long serialVersionUID = 1L;  
}  
